import Vue from "vue";
import VueRouter from "vue-router";
import store from "../store/index"

Vue.use(VueRouter)

//导入视图
import errers from "@/views/errers";
import adminUrl from "../views/admin/urls";
import loginUrl from "../views/login/urls";
import Cookies from "js-cookie";
import Ax from "../views/login/axios"

const ax = new Ax()

const routes = [
    {path: "/", redirect: "/admin"},
    //404路由
]

routes.push(adminUrl)
routes.push(loginUrl)

routes.push({path: "*", component: errers})


const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch((err) => err);
};
//创建路由实例
const router = new VueRouter({
    routes,
    mode:"history"  //路由模式
})


//定义全局路由全局守卫
router.beforeEach((to, from, next)=>{

    if (!Cookies.get("token") && to.path !== "/login"){
        next("/login")
    } else{
        //在这里要把用户的权限数据存在vuex

        if (store.state.login.perms.length === 0 || from.path === "/login"){
            //获取权限
            ax.getUserInfo({username:Cookies.get("username")}).then(response=>{
                store.state.login.perms = response.data.roles[0].perms
            }).catch(err=>{
                console.log(err.response)
            })
        }

        next()

    }



 })
//
// router.beforeResolve((to, from, next)=>{
//     next()
// })
//
// router.afterEach((to, from)=>{
// })


export default router